package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 销售额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();

        //计算出时间范围内的每一天的集合
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        
        //统计时间范围内的每一天的销售额
        for (LocalDate everyDay : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(everyDay, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(everyDay, LocalTime.MAX);
            //查询每天的营业额
            //select sum(count) from orders where order_time>beginTime and order_Time<endTime and status = 6
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("statue", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null?0:turnover;
            turnoverList.add(turnover);

        }
        //封装vo对象
        TurnoverReportVO reportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return reportVO;
    }


    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //构建三个返回用到的集合,日期,新增用户,总用户
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        //计算时间范围内的每一天的集合
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //统计每一天的新增用户数,总用户数
        for (LocalDate everyDay : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(everyDay, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(everyDay, LocalTime.MAX);

            //统计每日新增用户数
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer newUserCount = userMapper.countByMap(map);

            //统计截至日期为止的用户
            map.put("begin",null);
            Integer totalUserCount = userMapper.countByMap(map);
            newUserList.add(newUserCount);
            totalUserList.add(totalUserCount);


        }
        //VO封装
        UserReportVO reportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return reportVO;
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //创建三个集合,对应日期,每日有效订单,每日订单总数
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalOrderList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        //时间范围内的每日集合
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //每日有效订单和总订单数
        for (LocalDate everyDay : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(everyDay, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(everyDay, LocalTime.MAX);
            //统计订单数
            Map map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            Integer orderCount = userMapper.countByMap(map);
            map.put("status",Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            totalOrderList.add(orderCount);
            validOrderList.add(validOrderCount);
        }
        //汇总时间范围内的有效订单及总订单数
        Integer totalOrderCount = totalOrderList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();

        //求有效订单率
        Double orderCompletionRate = 0.0D;
        if(totalOrderCount!=0){
            orderCompletionRate =  1.0 * validOrderCount / totalOrderCount;
        }
        //封装VO
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(totalOrderList,","))
                .validOrderCountList(StringUtils.join(validOrderCount,","))
                .validOrderCount(validOrderCount)
                .totalOrderCount(totalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    /**
     * 指定时间区间内的排名统计top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //每日有效订单和总订单数
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()),",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()),",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 生成excel,导出数据
     * @return
     */
    @Override
    public XSSFWorkbook export() throws IOException {

        //获取模板输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/out.xlsx");

        //获取30天内的运行数据
        LocalDate today = LocalDate.now();
        LocalDate begin = today.minusDays(30);
        LocalDate end = today.minusDays(1);

        //创建excel对象
        XSSFWorkbook excel = new XSSFWorkbook(in);
        XSSFSheet sheet = excel.getSheetAt(0);

        //获取第二行
        sheet.getRow(1).getCell(1).setCellValue(begin+"至"+end);

        BusinessDataVO totalData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN)
                , LocalDateTime.of(end, LocalTime.MAX));

        XSSFRow row4 = sheet.getRow(3);
        row4.getCell(2).setCellValue(totalData.getTurnover());//获取营业额
        row4.getCell(6).setCellValue(totalData.getNewUsers());//获取新增用户数
        row4.getCell(4).setCellValue(totalData.getOrderCompletionRate());//获取完成率

        XSSFRow row5 = sheet.getRow(4);
        row5.getCell(2).setCellValue(totalData.getValidOrderCount());//获取有效订单
        row5.getCell(4).setCellValue(totalData.getUnitPrice());//获取平均客单价

        //获取30天内每一天的运行数据
        for (int i = 0; i < 30; i++) {
            BusinessDataVO everyData =workspaceService.getBusinessData(LocalDateTime.of(begin.plusDays(i),LocalTime.MIN)
                    ,LocalDateTime.of(begin.plusDays(i),LocalTime.MAX));
            XSSFRow row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(String.valueOf(begin.plusDays(i)));
            row.getCell(2).setCellValue(everyData.getTurnover());
            row.getCell(3).setCellValue(everyData.getValidOrderCount());
            row.getCell(4).setCellValue(everyData.getOrderCompletionRate());
            row.getCell(5).setCellValue(everyData.getUnitPrice());
            row.getCell(6).setCellValue(everyData.getNewUsers());
        }

        //封装excel对象
        return excel;
    }
}
